﻿
using System;
using n_HardModule;

namespace n_Keyboard
{

//键盘监控类
public static class Keyboard
{
	static KeyNote[] KeyNoteList;
	static int KLength;
	
	//初始化
	public static void Init()
	{
		KeyNoteList = new KeyNote[ 256 ];
		Clear();
	}
	
	//清除所有按键信息
	public static void Clear()
	{
		KLength = 0;
	}
	
	//运行并触发按钮持续按下事件
	public static void Run()
	{
		for( int i = 0; i < KLength; ++i ) {
			if( !KeyNoteList[i].Open ) {
				continue;
			}
			if( KeyNoteList[i].Press ) {
				
				KeyNoteList[i].Tick += 20;
				if( KeyNoteList[i].Tick >= KeyNoteList[i].MaxTick ) {
					KeyNoteList[i].Tick = 0;
					if( KeyNoteList[i].Target != null ) {
						if( (KeyNoteList[i].Target.DataList[n_SOblect.SObject.Addr_Event] & 0x02) == 0 ) {
							KeyNoteList[i].Target.DataList[n_SOblect.SObject.Addr_Event] |= 0x04;
						}
					}
				}
			}
		}
	}
	
	//设置按键目标
	public static void SetKeyTarget( HardModule sm )
	{
		KeyNoteList[KLength] = new KeyNote( sm );
		KeyNoteList[KLength].Target = sm;
		KLength++;
	}
	
	//按下了一个按键
	public static void KeyDown( int k )
	{
		for( int i = 0; i < KLength; ++i ) {
			if( !KeyNoteList[i].Open ) {
				continue;
			}
			if( KeyNoteList[i].KeyValue != k ) {
				continue;
			}
			if( !KeyNoteList[i].Press ) {
				KeyNoteList[i].Press = true;
				KeyNoteList[i].Tick = 0;
				if( KeyNoteList[i].Target != null ) {
					KeyNoteList[i].Target.DataList[n_SOblect.SObject.Addr_Event] |= 0x01;
					KeyNoteList[i].Target.DataList[n_SOblect.SObject.Addr_Event] |= 0x04;
				}
				break;
			}
		}
	}
	
	//松开指定按键
	public static void KeyUp( int k )
	{
		for( int i = 0; i < KLength; ++i ) {
			if( !KeyNoteList[i].Open ) {
				continue;
			}
			if( KeyNoteList[i].KeyValue != k ) {
				continue;
			}
			KeyNoteList[i].Press = false;
			if( KeyNoteList[i].Target != null ) {
				//KeyNoteList[i].Target.DataList[n_SOblect.SObject.Addr_Event] |= 0x02;
				KeyNoteList[i].Target.DataList[n_SOblect.SObject.Addr_Event] = 0x02;
			}
			break;
		}
	}
}
//键盘元素
public class KeyNote
{
	public int KeyValue;
	public bool Press;
	public HardModule Target;
	
	public bool Open;
	public int Tick;
	public int MaxTick;
	
	//构造函数
	public KeyNote( HardModule h )
	{
		h.myKeyNote = this;
		Target = h;
		
		Press = false;
		Tick = 0;
		Open = false;
		
		ResetKey();
	}
	
	//重新设置时间和按键
	public void ResetKey()
	{
		if( Target.ExtendValue == "" ) {
			return;
		}
		Open = true;
		
		string[] s = Target.ExtendValue.Split( ' ' );
		
		KeyValue = 0;
		if( s[0] == "空格" ) {
			KeyValue = (int)( ' ' );
		}
		else if( s[0] == "回车" ) {
			 KeyValue = (int)( '\n' );
		}
		else {
			KeyValue = (int)( s[0][0] );
		}
		
		MaxTick = int.Parse( s[1] );
	}
}
}


